package com.sven.idrivingfutureserver.util;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dyplsapi20170525.Client;
import com.aliyun.dyplsapi20170525.models.BindAxbRequest;
import com.aliyun.dyplsapi20170525.models.BindAxbResponse;
import com.aliyun.dyplsapi20170525.models.BindAxnRequest;
import com.aliyun.dyplsapi20170525.models.BindAxnResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @ClassName AliPhoneUtil
 * @Description
 * @Author 小张
 * @Date 2024/6/11 15:14
 * @Version 1.0
 **/
@Slf4j
@Component
public class AliPhoneUtil {

    // 阿里云账号的 accessKey 和 accessSecret
    private static final String accessKey = "LTAI5tSavPjxAZtf3Yfi5emN";
    private static final String accessSecret = "LS8WB1jXGFrhkCK98X3i51y2oM3XP0";

    // 隐私电话配置信息
    private static final String poolKey = "号码池key";

    private static final int expirationTime = 5 * 60; // 过期时长：秒

    // 短信配置信息
    private static final String signName = "车小二";
    private static final String smsNoPlateNumberTemplateCode = "SMS_468370430"; // 无车牌号短信模板
    private static final String smsPlateNumberTemplateCode = "SMS_468275400";   // 有车牌号短信模板

    private static Client apiClientInstance;
    private static com.aliyun.dysmsapi20170525.Client smsClientInstance;

    private static Client apiClient() {
        if (null == apiClientInstance) {
            Config config = new Config()
                    .setAccessKeyId(accessKey)
                    .setAccessKeySecret(accessSecret);
            config.endpoint = "dyplsapi.aliyuncs.com";
            try {
                apiClientInstance = new Client(config);
            } catch (Exception e) {
                log.error("create apiClient error: {}", e.getMessage());
                throw new RuntimeException(e);
            }
        }
        return apiClientInstance;
    }

    /**
     * TODO: 获取一个可用的隐私号码
     */
    public String getPhoneX() {
        return "Todo";
    }

    /**
     * 绑定 虚拟号X 与 号码A
     * @return 成功失败
     */
    public boolean bindAxN(String phoneA, String phoneX) {
        BindAxnRequest bindAxnRequest = new BindAxnRequest()
                .setPoolKey(poolKey)
                .setPhoneNoA(phoneA)
                .setPhoneNoX(phoneX)
                .setExpiration(DateUtil.getSecondsAfterTime(expirationTime));
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        try {
            BindAxnResponse response = apiClient().bindAxnWithOptions(bindAxnRequest, runtimeOptions);
            return StringUtils.equals("OK", response.getBody().code);
        } catch (TeaException error) {
            log.error("绑定AxN失败 TeaException：{}", error.message);
        } catch (Exception  error) {
            log.error("绑定AxN失败 Exception：{}", error.getMessage());
        }
        return false;
    }

    public boolean bindAxB(String phoneA, String phoneB, String phoneX) {
        BindAxbRequest bindAxbRequest = new BindAxbRequest()
                .setPoolKey(poolKey)
                .setPhoneNoA(phoneA)
                .setPhoneNoX(phoneX)
                .setPhoneNoB(phoneB)
                .setExpiration(DateUtil.getSecondsAfterTime(expirationTime));
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        try {
            BindAxbResponse response = apiClient().bindAxbWithOptions(bindAxbRequest, runtimeOptions);
            return StringUtils.equals("OK", response.getBody().code);
        } catch (TeaException error) {
            log.error("绑定AxB失败 TeaException：{}", error.message);
        } catch (Exception  error) {
            log.error("绑定AxB失败 Exception：{}", error.getMessage());
        }
        return false;
    }

    private static com.aliyun.dysmsapi20170525.Client smsClient() {
        if (null == smsClientInstance) {
            Config config = new Config()
                    .setAccessKeyId(accessKey)
                    .setAccessKeySecret(accessSecret);
            config.endpoint = "dysmsapi.aliyuncs.com";
            try {
                smsClientInstance = new com.aliyun.dysmsapi20170525.Client(config);
            } catch (Exception e) {
                log.error("create apiClient error: {}", e.getMessage());
                throw new RuntimeException(e);
            }
        }
        return smsClientInstance;
    }


    /**
     * 发送短信
     * @param phoneNumber 目标手机号
     * @return 是否成功
     */
    public boolean sendSms(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            log.error("手机号信息有误：{}", phoneNumber);
            return false;
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(smsNoPlateNumberTemplateCode)
                .setPhoneNumbers(phoneNumber);
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        try {
            SendSmsResponse response = smsClient().sendSmsWithOptions(sendSmsRequest, runtimeOptions);
            log.info("SendSmsResponse: code: {}, message {}", response.getBody().code, response.getBody().getMessage());
            return StringUtils.equals("OK", response.getBody().code);
        } catch (TeaException error) {
            log.error("发送短信失败 TeaException：{}", error.message);
        } catch (Exception  error) {
            log.error("发送短信失败 Exception：{}", error.getMessage());
        }
        return false;
    }

    /**
     * 发送短信
     * @param phoneNumber 目标手机号
     * @param plateNumber 车牌号
     */
    public boolean sendSms(String phoneNumber, String plateNumber) {
        if (StringUtils.isEmpty(phoneNumber) || StringUtils.isEmpty(plateNumber)) {
            log.error("手机号/车牌号信息有误：{},{}", phoneNumber, plateNumber);
            return false;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("code", plateNumber);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateParam(JSON.toJSONString(map))
                .setTemplateCode(smsPlateNumberTemplateCode)
                .setPhoneNumbers(phoneNumber);
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        try {
            SendSmsResponse response = smsClient().sendSmsWithOptions(sendSmsRequest, runtimeOptions);
            log.info("SendSmsResponse: code: {}, message {}", response.getBody().code, response.getBody().getMessage());
            return StringUtils.equals("OK", response.getBody().code);
        } catch (TeaException error) {
            log.error("发送短信失败 TeaException：{}", error.message);
        } catch (Exception  error) {
            log.error("发送短信失败 Exception：{}", error.getMessage());
        }
        return false;
    }

}
